package cn.itcast.ft.controller;

import cn.hutool.extra.mail.MailUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itcast.config.VisibleThreadPoolTaskExecutor;
import cn.itcast.ft.dto.*;
import cn.itcast.ft.entity.FTToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("bb")
@Slf4j
public class BBController {
    public static List<FTToken> tokenList=new ArrayList<>();
    @Autowired
    private VisibleThreadPoolTaskExecutor executor;

    /**
     * 神凤：47，虎首：49，五爪神龙：46，龙珠：45，龙灵：33，猪首：48，青龙：34，天庭一偶:50
     * @param num
     * @param salePrice
     * @param page
     * @param goodsId
     * @return
     */
    @RequestMapping("/wzhCreateMarket")
    public String wzhCreateMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                                  @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                                  @RequestParam(value = "page",defaultValue = "1") Integer page,
                                  @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        FTToken token4=new FTToken();
        String token="Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6OTA1OCwibW9iaWxlIjoiMTM4MDM5OTM5MTkiLCJyZWFsbmFtZSI6IuWImOWutuS4hyIsImp0aSI6Ims0dzYzeXh6aXRrZm1rdWJtN2toMmRqbmhzdTFpMSIsImlzcyI6OTA1OCwiZXhwIjoxNzMzNDY3NzAwLCJuYmYiOjE3MzIxNzE3MDAsImlhdCI6MTczMjE3MTcwMCwic3ViIjoid2ViIiwiYXVkIjoid2ViIn0.85qhq9AxCs_WLWGzX5i6G_bYdnsG1hDGTNuKPcBbCVI";
        token4.setToken(token);
        token4.setRefreshToken("微信名字:万");
        tokenList.add(token4);
        if(!CollectionUtils.isEmpty(tokenList)) {
            for (int i = 0; i < num; i++) {
                try {
                    for (int z = 0; z < tokenList.size(); z++) {
                        Proxy proxy = null;
                        confireMarketOrder(proxy, tokenList.get(z), goodsId, salePrice,page);
                        Thread.sleep(2000);
                    }
                } catch (Exception e) {
                    log.error("#####异常####" + e.getMessage());
                }
            }
            log.info("####FT执行完成#####");
        }
        return null;
    }
    public void confireMarketOrder(Proxy proxy,FTToken token,String goodsId,String salePrice,Integer page){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice,page);
        }catch (Exception e){
            log.error("#####获取商品失败####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,FTToken token,String goodsId,String salePrice,Integer page) throws InterruptedException {
        String result=null;
        BBOrderDTO goodsDTO=null;
        JSONObject jsonObject=new JSONObject();
        jsonObject.putOnce("id",goodsId);
        Map<String,Integer> params=new HashMap<>(16);
        params.put("current",1);
        params.put("pageSize",100);
        jsonObject.putOnce("params",params);
        Map<String,String> sort=new HashMap<>(16);
        sort.put("price","ascend");
        jsonObject.putOnce("sort",sort);
        String jsonString=jsonObject.toString();
        try{
            result = HttpRequest.post("https://backend.artbaobao.com/api/market/sales")
                    .body(jsonObject.toString())
                    .header("authorization",token.getToken())
                    .execute().body();
            goodsDTO= JSONUtil.toBean(result,BBOrderDTO.class);
        }catch (Exception e){
            log.error("##获取商品数据异常###:"+e.getMessage()+"####返回数据：###"+result);
        }
        if(goodsDTO.getCode()==200){
            if(goodsDTO.getData()!=null && !CollectionUtils.isEmpty(goodsDTO.getData().getList())){
                List<BBOrderDetailListDTO> list=goodsDTO.getData().getList();
                for(BBOrderDetailListDTO detailDTO:list){
                    if(detailDTO.getPrice().compareTo(new BigDecimal(salePrice))<=0){
                        Proxy finalProxy = proxy;
                        executor.execute(()->{
                            saveOrder(finalProxy,token,goodsId,detailDTO);
                        });
                        Thread.sleep(1000);
                    }

                }
            }
        }

    }

    public void saveOrder(Proxy proxy,FTToken token,String goodsId,BBOrderDetailListDTO detailDTO){
        BBConfirmOrderDTO responseDTO=null;
        String response=null;
        try{
            JSONObject jsonObject=new JSONObject();
            jsonObject.putOnce("id",goodsId);
            jsonObject.putOnce("tokenId",detailDTO.getId());
            response = HttpRequest.post("https://backend.artbaobao.com/api/market/order")
                    .header("authorization",token.getToken())
                    .body(jsonObject.toString())
                    .execute().body();
            log.info("#####确认订单结果####"+response);
            responseDTO= JSONUtil.toBean(response,BBConfirmOrderDTO.class);
            if(responseDTO.getCode()==200){
                MailUtil.send("1027060531@qq.com", "收到订单", "您有一个订单:"+token.getRefreshToken()+"，请赶紧支付！", false);
            }
        }catch (Exception e){
            log.error("###确认订单失败###:"+e.getMessage()+",goodsId:"+goodsId+":"+detailDTO.toString()+"##返回的参数信息##:"+response+",#######:"+token);
        }

    }

    @RequestMapping("/jk_pt_addUser")
    public String wzhCreateMarket(
            @RequestParam(value = "account") String account,
            @RequestParam(value = "wx") String wx,
            @RequestParam(value = "password") String password) {
        String response=null;
        WKUserDTO goodsDTO=null;
        try{
            JSONObject jsonObject=new JSONObject();
            jsonObject.putOnce("account",account);
            jsonObject.putOnce("password",password);
            response = HttpRequest.post("https://duoliang.cc/api/login")
                    .body(jsonObject.toString())
                    .execute().body();
            log.info("#####确认订单结果####"+response);
            goodsDTO= JSONUtil.toBean(response,WKUserDTO.class);
        }catch (Exception e){
            log.error("##获取商品数据异常###:"+e.getMessage()+"####返回数据：###"+response);
        }
        if(goodsDTO.getStatus()==200){
            FTToken token4=new FTToken();
            String token="Bearer "+goodsDTO.getData().getToken();
            token4.setToken(token);
            token4.setRefreshToken("微信名字:"+wx);
            tokenList.add(token4);
        }else{
            log.error("##账号密码错###:"+wx);
        }
        return null;
    }
}
